const app = getApp();
const utils = require('../../../utils/util.js');
Page({
  data: {
    cardUser: {cid:0, mobile: '', saleUid:0}, //玖玖卡
    CurrentPage: 1,
    loadingMore: 1,
    cityId: 0,
    cateId: 0,
    key: '',
    lng: 0,
    lat: 0,
    shopInfo: {shopPower:0, pricePerson: 0},
    dealList: [],   //套餐列表
    dealList2:[],   //代金券列表
    isAccredit: false,  //是否已经授权头像昵称
    canIUseGetUserProfile: false, 
  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function (e) { 
    let that = this;
    that.setData({
      cityId: e.cityId,
      key: e.key,   
    })
    if(e.cateId){
      that.setData({cateId: e.cateId})
    }
    if(e.lng && e.lat){
      that.setData({
        lng: e.lng,
        lat: e.lat,   
      })
    }
    if(!e.cityId){
      utils.showToast('缺少参数，请重新分享');
      return;
    }
    if(app.globalData.isFriendState == 1){  
      that.search();   //朋友圈打开
      return;
    }
    if (wx.getUserProfile) {
      this.setData({canIUseGetUserProfile: true})
    }

    utils.authLogin(()=>{
      that.getJJKInfo();
      that.getMyCard(); 
      utils.getLocation((location)=>{
        that.data.lng = location.lng;
        that.data.lat = location.lat;
        that.search();
      }); 
      //是否授权了头像
      utils.isAccredit(function (isAccredit) {
        that.setData({isAccredit: isAccredit})
      });   
      if(e.revUid){
        that.receiveJJK(e.revUid);  //带此参数,自动领玖玖卡 2022-04-11
      }
    });    
  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow: function (){
  },

  //商家搜索
  search: function(){
    let that = this;
    let uid = app.globalData.isFriendState == 1 ? 0 : app.globalData.userInfo.Uid;
    wx.showLoading({title: '加载中...',mask: true})
    wx.request({
      url: app.globalData.host + '/api/meituan/search' ,
      data: {
        uid: uid,
        key: that.data.key,
        cityId: that.data.cityId,
        cateId: that.data.cateId,
        sortType: 7,
        lng: that.data.lng,
        lat: that.data.lat,
      },
      success: function (res) {
        wx.hideLoading();
        if (res.data.Code == 0) {
          let dealList = [];  //套餐
          let dealList2 = []; //代金券
          let shopInfo = that.data.shopInfo;
          if(res.data.Data.Items==0){
            utils.showToast('数据不存在');
            return;
          }
          for(let i = 0; i < res.data.Data.Items.length; i++){          
            let item =  res.data.Data.Items[i];        
            item.DealBaseInfo.discountPrice = ((item.DealBaseInfo.marketPrice -item.DealBaseInfo.realPrice) /100).toFixed(2); //优惠金额
            item.DealBaseInfo.realPrice = (item.DealBaseInfo.realPrice/100).toFixed(2);
            item.DealBaseInfo.marketPrice = (item.DealBaseInfo.marketPrice/100).toFixed(0);
            item.DealBaseInfo.miniUrl= item.CouponInfo.miniProgramUrl;  //小程序链接
            item.ShopInfo.pricePerson = (item.ShopInfo.pricePerson/100).toFixed(0);
            item.ShopInfo.shopPowers=[];         
            for(let j=0; j<50; j+= 10){
              let num = item.ShopInfo.shopPower - j;
              if(num >= 10){
                item.ShopInfo.shopPowers.push('star10.png'); //满星
              }else if(num < 10 & num > 0){
                item.ShopInfo.shopPowers.push('star5.png');  //半颗星
              }else if(num < 10){
                item.ShopInfo.shopPowers.push('star0.png');  //没星
              }             
            }
            if(item.ShopInfo.distance > 1000){
              item.ShopInfo.distance = Math.round(item.ShopInfo.distance/100)/10  + ' km'
            }else{
              item.ShopInfo.distance += ' m';
            }  
            if(item.DealBaseInfo.dealType == 1){
              dealList.push(item.DealBaseInfo); //套餐
            }
            if(item.DealBaseInfo.dealType == 2){
              dealList2.push(item.DealBaseInfo);  //代金券
            }
            if(i == 0){
              shopInfo = item.ShopInfo;
              shopInfo.defaultPic = item.DealBaseInfo.defaultPic
            }    
          }
      
          that.setData({
            shopInfo: shopInfo,
            dealList: dealList,
            dealList2: dealList2,
          })
        } else {
          utils.showModal(res.data.Message);
        }
      }
    })
  },
  //跳转到美团领券
  receive: function(e){
    let that = this;
    console.log(e.currentTarget)
    let index = e.currentTarget.dataset.index;
    let dealType = e.currentTarget.dataset.type;
    //美团小程序路径
    let url = dealType == 1 ?  that.data.dealList[index].miniUrl : that.data.dealList2[index].miniUrl;
    wx.navigateToMiniProgram({
      appId: 'wxde8ac0a21135c07d',
      path: url
    })
  },  
  toMap: function(e){
    let that = this;
    if(that.data.lat <= 0 || that.data.lng <= 0){
      utils.showToast('请重新打开页面再重试')
      return;
    }
    wx.openLocation({
      latitude: that.data.lat,
      longitude: that.data.lng,
      scale: 28,
      name: "点击右边打开地图导航",
      address: that.data.shopInfo.address
    })      
  },
  
  getMyCard: function () {
    let that = this;
    wx.request({
      url: app.globalData.host + '/api/Staff/GetStaffIdByUid?Uid=' + app.globalData.myUserInfo.Uid,
      success: function (res) {
        if (res.data.Code == 0) {
          if (res.data.Data) {         
            that.data.shareTitle = res.data.Data.Company;                
          }
        }
      },
    })
  },

  getJJKInfo: function () {
    let that = this;
    wx.request({
      url: app.globalData.host + '/api/Coupon/GetCardExists?uid=' + app.globalData.userInfo.Uid,
      success: function (res) {
        if (res.data.Code == 0) {
          var item = res.data.Data;
          if (res.data.Data) {
            that.setData({
              cardUser: {cid: item.Cid,saleUid: item.SaleUid,mobile: item.Phone}
            })
          }
        } else {
          utils.showModal(res.data.Message);          
        }
      }
    })
  },
  //领玖玖卡
  receiveJJK: function (saleUid) {
    let that = this;
    if (app.globalData.userInfo) {
      let jjCard = app.globalData.jjCard;
      wx.request({
        url: app.globalData.host + '/api/Coupon/ReceiveCard?code=0&cardItemId=' + jjCard.Id + '&uid=' + app.globalData.userInfo.Uid + '&saleUid=' + saleUid,
        success: function (res) {                 
        }
      })
    } else {
      setTimeout(function () {
        that.receiveJJK(saleUid);
      }, 1000)
    }
  },
  /**
   * 用户点击右上角分享
   */
  onShareAppMessage: function (e) {
    let that = this;
    let path='/pages/meituan/detail/index';
    if (that.data.shareTitle) {
      path += '?cityId=' + that.data.cityId + '&cateId=' + that.data.cateId + '&revUid=' + app.globalData.myUserInfo.Uid + '&key=' + that.data.key;
    }else if(that.data.cardUser.saleUid > 0){
      path += '?cityId=' + that.data.cityId + '&cateId=' + that.data.cateId + '&revUid=' + that.data.cardUser.saleUid + '&key=' + that.data.key;
    }
    console.log(path);  
    return {
      imageUrl: '',
      title: that.data.shopInfo.shopName,
      path: path,
      success: function (res) {
        utils.showModal('分享成功');
      }
    }
  },
  //分享朋友圈
  onShareTimeline: function () {
    let that = this;
    let path='';   
    //带上分享人的坐标，防止加载没数据
    if (that.data.shareTitle) {
      path += 'cityId=' + that.data.cityId + '&revUid=' + app.globalData.myUserInfo.Uid + '&cateId=' + that.data.cateId + '&key=' + that.data.key + '&lat=' + that.data.lat + '&lng=' + that.data.lng + '&isFriend=1';
    }else if(that.data.cardUser.saleUid > 0){
      path += 'cityId=' + that.data.cityId  + '&revUid=' + that.data.cardUser.saleUid + '&cateId=' + that.data.cateId + '&key=' + that.data.key + '&lat=' + that.data.lat + '&lng=' + that.data.lng + '&isFriend=1';
    }
    return {
      title: that.data.shopInfo.shopName,
      imageUrl: that.data.shopInfo.defaultPic,
      query:  path
    }
  },
   // 复制地址
   copyAddress: function (e) {
    let data = e.currentTarget.dataset.address;
    wx.setClipboardData({
      data: data,
      success(res) {        
        utils.showToast('地址已复制','success');
      }
    })
  },  
  //授权头像昵称
  getUserProfile: function (e) {
    let that = this;
    wx.getUserProfile({
      desc: '用于完善会员资料', 
      success: (res) => {
        utils.AuthorizeUserInfo(res, '', function (flag) {
          that.setData({isAccredit: flag});
          utils.showToast('已授权,请重新领取');
        });   
      }
    })
  }
})